import NewTaskStep1 from './NewTaskStep1'
import NewTaskStep2 from './NewTaskStep2'
import NewTaskStep3 from './NewTaskStep3'
import { mapState, mapMutations } from 'vuex'
const cancleBtn = {
    key: '',
    title: 'cancel',
    type: 'info',
    name: 'cancelBtn',
    method: null,
    callback: null,
    loading: false,
    disabled: false,
}
const preBtn = {
    key: '',
    title: 'previous',
    type: 'primary',
    name: 'preBtn',
    method: null,
    callback: null,
    loading: false,
    disabled: false,
}
const nextBtn = {
    key: '',
    title: 'next',
    type: 'primary',
    name: 'nextBtn',
    method: null,
    callback: null,
    loading: false,
    disabled: false,
}
const saveBtn = {
    key: '',
    title: 'sure',
    type: 'primary',
    name: 'saveDataBtn',
    method: null,
    callback: null,
    loading: false,
    disabled: false,
}
const taskBase = {
    data() {
        const _this = this
        return {
            cancleBtn,
            step1config: {
                // 右侧抽屉框要呈现的组件
                compName: NewTaskStep1,
                title: `${_this.$t('buildCampaign')}: ${_this.$t('basicSetting')}`,
                width: 'large',
                footerButtons: [{...nextBtn, method: _this.nextStep }, {...cancleBtn }],
                showFooter: true,
                onClose: () =>{
                  _this.RESET_NEWTASK_DATA(this.upgradeTriggerType);
                }
            },
            step2config: {
                // 右侧抽屉框要呈现的组件
                compName: NewTaskStep2,
                title: `${_this.$t('buildCampaign')}: ${_this.$t('selectVehicle')}`,
                width: 'large',
                footerButtons: [{...preBtn, method: _this.preStep }, {...nextBtn, method: _this.nextStep }, {...cancleBtn }],
                showFooter: true,
                onClose: () =>{
                  _this.RESET_NEWTASK_DATA(this.upgradeTriggerType);
                }
            },
            step3config: {
                // 右侧抽屉框要呈现的组件
                compName: NewTaskStep3,
                title: `${_this.$t('buildCampaign')}: ${_this.$t('taskSetting')}`,
                width: 'large',
                footerButtons: [{...preBtn, method: _this.preStep }, {...saveBtn, method: _this.saveData }, {...cancleBtn }],
                showFooter: true,
                onClose: () =>{
                  _this.RESET_NEWTASK_DATA(this.upgradeTriggerType);
                }
            },
            drawerConfigT: this.step1config,
            upgradeTriggerType : ''
        }
    },
    computed: {
        ...mapState({
            stepNum: (state) => state.newTask.stepNum,
            // upgradeTriggerTypeGlobal: (state) => state.newTask.upgradeTriggerType,
            prevStepNum: (state) => state.newTask.prevStepNum,
            newTaskDataAll: (state) => state.newTask.newTaskData,
            taskFileConfig: (state) => state.newTask.taskFileConfig,
            userId: (state) => state.user.userId,
        }),
      newTaskData(){
        return this.newTaskDataAll[this.upgradeTriggerType];
      },
    },
    watch: {
        stepNum(value) {
            // this.getCurrentStepConfig(value)
        },
      'newTaskData.channel'(val) {
        if (val === 1) {
          //规划院
        }
        this.getCurrentStepConfig(this.stepNum);
      }
    },
    mounted() {},
    methods: {
        ...mapMutations([
            // 'resetDrawerConfig',
            'RESET_NEWTASK_DATA',
            // 'SET_UPGRADE_TRIGGER_TYPE',
            // 'setDrawerConfig',
            // 'toggleDrawerMain',
            'SET_STEPNUM',
            'SET_PREV_STEPNUM',
        ]),
        getCurrentStepConfig(value) {
            this.drawerConfigT = [this.step1config, this.step2config, this.step3config][value]
            let config = {...this.drawerConfigT};
            if (this.newTaskData.channel === 0 && this.drawerConfigT === this.step1config) {
              //工程院通道第一步提供提交按钮、去除下一步按钮
              config.footerButtons = [...this.drawerConfigT.footerButtons];
              config.footerButtons.splice(0, 1, {...saveBtn, method: this.saveData })
            }
            config.vars = {upgradeTriggerType: this.upgradeTriggerType};
            // let title = this.drawerConfigT.title
            this.setDrawerConfig(config)
        },
        // 上一步
        preStep() {
            if (this.stepNum > 0) {
                this.SET_PREV_STEPNUM(this.stepNum)
              //对接工程院，新建任务第二步（选择车辆）跳过
              if (this.stepNum === 2 && this.newTaskData.channel === 0) {
                this.SET_STEPNUM(this.stepNum - 2);
              } else {
                this.SET_STEPNUM(this.stepNum - 2);
                // this.SET_STEPNUM(this.stepNum - 1);
              }
              this.getCurrentStepConfig(this.stepNum)
            }
        },
        // 下一步
        nextStep(comp) {
            comp.getFormValid().then(() => {
                if (this.stepNum < 2) {
                  this.SET_PREV_STEPNUM(this.stepNum)
                  //对接工程院，新建任务第二步（选择车辆）跳过
                  if (this.stepNum === 0 && this.newTaskData.channel === 0) {
                    this.SET_STEPNUM(this.stepNum + 2);
                  } else {
                    this.SET_STEPNUM(this.stepNum + 2);
                    // this.SET_STEPNUM(this.stepNum + 1);
                  }
                  this.getCurrentStepConfig(this.stepNum)
                }
            })
        },
        // 提交新建任务
        saveData(res) {
            const vm = this
            const params = {
                name: vm.newTaskData.name,
                startTime: vm.newTaskData.startTimeStr,
                endTime: vm.newTaskData.endTimeStr,
                strategyId: vm.newTaskData.strategyId,
                factoryChannel: vm.newTaskData.factoryChannel,
                remark: vm.newTaskData.remark,
                auditItems: res.auditItems,
                taskGrayPush: res.grayscaleItem,
                type: vm.newTaskData.type, // 1 用户 2 自动
                recordNo: vm.newTaskData.recordNo, // 备案号
                // 任务审核节点审批用户配置列表
                candidates: res.candidates
            }
            if (vm.newTaskData.type === '1') {
                // 强制 非强制
                params.forceUpgrade = vm.newTaskData.forceUpgrade
            } else {
                // 静默 非静默
                params.silenceUpgrade = vm.newTaskData.silenceUpgrade
            }
            if (vm.newTaskData.choseType === 2) {
                // 来自文件
                params.vehicleSourceType = 3
                    //   文件预处理
                params.pretreatmentId = vm.newTaskData.pretreatmentId
            } else if (vm.newTaskData.choseType === 1) {
                // 批量选择
                if (vm.newTaskData.isSlefSelect) {
                    // 自定义勾选
                    params.vehicleSourceType = 2
                        // 自定义勾选车辆id
                    params.vehicleIds = vm.newTaskData.selectCarIds
                } else {
                    // 批量全部
                    params.vehicleSourceType = 1
                        // 筛选条件 车辆类型 省份 vin
                    params.vehicleType = vm.newTaskData.queryParam.vehicleType
                    params.province = vm.newTaskData.queryParam.province
                    params.vin = vm.newTaskData.queryParam.vin
                }
            }
            //taskGcyExt 处理
          params.taskGcyExt = {...vm.newTaskData.taskGcyExt};
          params.taskGcyExt.upgradeAccessProve = [...vm.newTaskData.taskGcyExt.upgradeAccessProve].map(file => file.id);
          vm.taskFileConfig.forEach(item => {
            params.taskGcyExt[item.key] = [...vm.newTaskData.taskGcyExt[item.key]].map(file => file.id);
            params.taskGcyExt[item.reasonKey] = vm.newTaskData.taskGcyExt[item.reasonKey];
            params.taskGcyExt[item.boolKey] = vm.newTaskData.taskGcyExt[item.boolKey];
            if (vm.newTaskData.taskGcyExt[item.boolKey] === false) {
              params.taskGcyExt[item.key] = [];
            }
          });
          if (vm.newTaskData.channel === 1) {
            //规划院写死工程院审批人
            params.taskGcyExt.applyUserId='1';
            params.taskGcyExt.auditUserId='1';
            params.taskGcyExt.batchName=params.name;
          }
          let post = vm.$api.addTaskData;
          if (this.upgradeTriggerType === 'warehouse') {
            params.items = [
              {
                code:'duration',
                value: vm.newTaskData.duration
              }
            ]
            params.taskGcyExt.updateScope = ['厂内库存升级']
            // 成品库任务创建时取当前登录用户的userId
            params.taskGcyExt.applyUserId=this.userId
            post = vm.$api.addWarehouseTask;
          }
            return new Promise((resolve, reject) => {
              post(params)
                    .then((res) => {
                        if (res.code === 0) {
                            // 重置新建数据
                            vm.RESET_NEWTASK_DATA(this.upgradeTriggerType);
                            // 关闭弹框重置弹框配置
                            vm.toggleDrawerMain(false)
                            vm.resetDrawerConfig()
                            // 刷新任务列表
                            vm.refreshData(true)
                            vm.distributionStatusDate() // 更新饼图
                            resolve(res)
                            return;
                        }
                        reject(res)
                    })
                    .catch((err) => {
                        reject(err)
                    })
            });
        },
    },
}
export { taskBase }